//
//  CTV.m
//  Channltv
//
//  Created by Bruno Keymolen on 7/5/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTV.h"
#import "CTVAutoSync.h"

@implementation CTV

+(id)GetInstance {
	static id _CTVSingleton = nil;
	if (_CTVSingleton == nil) {
		_CTVSingleton = [self new];
		[_CTVSingleton setup];
	}	
    return _CTVSingleton;
}



 -(void)setup{
	

	//Create and bind the necessary components	
	m_imgman = [BRImageManager sharedInstance];
	
	//Config
	m_config = [CTVConfig GetInstance];
	
	//RootCannels : My Channels, Friends Channels, Private Home Channels		
	m_rootChannels = [[NSMutableDictionary alloc] init];
							
	m_myChannels = [[NSMutableArray alloc]init];
	//m_myTopChannels = [NSMutableArray new];
	
	//Load the first menu
	[[CTVSync GetInstance] syncChannelsFromDisk];
	
	//Start autosync
	[[CTVAutoSync GetInstance] start];
	[[CTVAutoSync GetInstance] syncNow];
	
	
 }


-(void) dealloc{ 
	CTVRootChannel* rootChannel;
	NSString* key;
	NSEnumerator* rootChannelKeys = [m_rootChannels objectEnumerator];
	while(key = [rootChannelKeys nextObject]){
		rootChannel = [m_rootChannels objectForKey:key];
		[rootChannel release];
	}
	[m_rootChannels release];
	
	
	[m_myChannels removeAllObjects];		
	[m_myChannels release];

	[super dealloc]; //do not forget to transmit to the superclass 
} 

-(NSMutableDictionary*)rootChannels{
	return m_rootChannels;
}

 
//-(CTVChannel*)GetChannel{
//	return [m_rss CreateChannelFromXML];
//}


-(NSMutableArray*)myChannels{
	return m_myChannels;
}

-(NSMutableArray*)myTopChannels{
	return m_myTopChannels;
}

-(BRImageManager*)imgman{
	return m_imgman;
}


-(int)cacheImg:(NSString*)imgPath{
return 0;
	NSURL * imageURL = [NSURL URLWithString: imgPath];
  
    NSString* imageName = [m_imgman imageNameFromURL: imageURL] ;

    if ( [m_imgman isImageAvailable: imageName] == NO )
    {
        // register for notifications and start downloading
        [[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: nil /*@selector(imageLoaded:)*/
                                             name: @"BRAssetImageUpdated"
                                           object: nil];

        // this will begin the background download
        [m_imgman writeImageFromURL: imageURL];
    }
    	
	return 0;
}


-(CGImageRef)getCGIImage:(NSString*)imgPath{
	BRImageManager * mgr = [BRImageManager sharedInstance];
    NSURL * imageURL = [NSURL URLWithString:imgPath]; 
    NSString* imageName = [mgr imageNameFromURL:imageURL];

    if ( [mgr isImageAvailable: imageName] == YES ){
		return [mgr imageNamed: imageName];
	}	
	
	return nil;
}



@end
